# This Python file uses the following encoding: utf-8
import urllib2
import re
from PIL import Image
import win32gui
import win32con
import win32api

# 从网络获取数据
def connect_Net(strUrl) :
    response = urllib2.urlopen(strUrl)
    data = response.read()
    return data
#g_img={url: "/az/hprichbg/rb/Forest_ZH-CN16430313748_1920x1080.jpg"
# :url(/az/hprichbg/rb/LaGrandeNomade_ZH-CN10098798714_1920x1080.jpg)
# 获取URL
def get_DailyPicUrl(data) :
    #r'^g_img=(url:"*?jpg")'
#url: "/az/hprichbg/rb/HallstattAustria_ZH-CN10534000934_1920x1080.jpg"
    patternImg = r'url: "(.*jpg)"'
    patternUrl = r'url:"(.*?jpg)"'
    pattern = r'(/az/[^s]*?jpg)'
    picUrl = re.findall(patternImg, data);
    return picUrl[0];


#http://cn.bing.com/az/hprichbg/rb/GreatSaltLake_ZH-CN12553220159_1920x1080.jpg
def download_DailyPic(picUrl) :
    # 地址
    picUrl = 'http://cn.bing.com' + picUrl
    picData = connect_Net(picUrl)
    # 图片列表
    picList = str(picUrl).split('/')
    picName = picList[len(picList) - 1]
    # 保存到本地
    with open(picName, 'wb') as f:
        f.write(picData)
    print ('download successed~')
    return picName
    
StoreFolder = "D:\\Learn\\Python\\wallpaper"

    
def setWallPaper(imagePath):
    bmpImage = Image.open(imagePath)
    newPath = StoreFolder + "\\" +imagePath
    bmpImage.save(newPath, "BMP")
    setWallpaperFromBMP(newPath)


def setWallpaperFromBMP(imagepath):
    print imagepath
    k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") #2������Ӧ����,0�������
    win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)
  

if __name__ == '__main__' :
    data = connect_Net('https://www.bing.com/?mkt=zh-CN')
    picUrl = get_DailyPicUrl(data.decode('utf-8'))
    picName = download_DailyPic(picUrl)
    setWallPaper(picName)
    
